import sys
from PyQt5.QtWidgets import (QApplication, QDialog, QVBoxLayout, QHBoxLayout,
                             QLabel, QLineEdit, QPushButton, QMessageBox,
                             QCheckBox)
from PyQt5.QtCore import Qt, QSettings
from PyQt5.QtGui import QIcon


class LoginDialog(QDialog):
    def __init__(self, parent=None):
        super(LoginDialog, self).__init__(parent)
        self.setWindowTitle("用户登录")
        self.setFixedSize(300, 200)
        self.setWindowFlags(Qt.Dialog | Qt.CustomizeWindowHint | Qt.WindowTitleHint)

        # 初始化UI
        self.init_ui()

        # 加载保存的登录信息
        self.load_saved_credentials()

    def init_ui(self):
        layout = QVBoxLayout()

        # 用户名
        username_layout = QHBoxLayout()
        username_layout.addWidget(QLabel("用户名:"))
        self.username_edit = QLineEdit()
        self.username_edit.setPlaceholderText("请输入用户名")
        username_layout.addWidget(self.username_edit)
        layout.addLayout(username_layout)

        # 密码
        password_layout = QHBoxLayout()
        password_layout.addWidget(QLabel("密码:"))
        self.password_edit = QLineEdit()
        self.password_edit.setPlaceholderText("请输入密码")
        self.password_edit.setEchoMode(QLineEdit.Password)
        password_layout.addWidget(self.password_edit)
        layout.addLayout(password_layout)

        # 记住密码和自动登录
        self.remember_check = QCheckBox("记住密码")
        self.auto_login_check = QCheckBox("自动登录")
        layout.addWidget(self.remember_check)
        layout.addWidget(self.auto_login_check)

        # 按钮
        button_layout = QHBoxLayout()
        self.login_btn = QPushButton("登录")
        self.login_btn.clicked.connect(self.authenticate)
        self.cancel_btn = QPushButton("取消")
        self.cancel_btn.clicked.connect(self.reject)
        button_layout.addWidget(self.login_btn)
        button_layout.addWidget(self.cancel_btn)
        layout.addLayout(button_layout)

        self.setLayout(layout)

    def load_saved_credentials(self):
        # 从设置中加载保存的凭据
        settings = QSettings("MyCompany", "MyApp")
        username = settings.value("username", "")
        password = settings.value("password", "")
        remember = settings.value("remember_password", False, type=bool)
        auto_login = settings.value("auto_login", False, type=bool)

        if username:
            self.username_edit.setText(username)
        if remember and password:
            self.password_edit.setText(password)
            self.remember_check.setChecked(True)

        self.auto_login_check.setChecked(auto_login)

        # 如果启用了自动登录，尝试自动登录
        if auto_login and username and password:
            self.auto_login()

    def save_credentials(self):
        # 保存凭据到设置
        settings = QSettings("MyCompany", "MyApp")
        if self.remember_check.isChecked():
            settings.setValue("username", self.username_edit.text())
            settings.setValue("password", self.password_edit.text())
            settings.setValue("remember_password", True)
        else:
            settings.remove("username")
            settings.remove("password")
            settings.setValue("remember_password", False)

        settings.setValue("auto_login", self.auto_login_check.isChecked())

    def authenticate(self):
        username = self.username_edit.text()
        password = self.password_edit.text()

        # 简单的验证逻辑 - 实际应用中应该更复杂
        if not username or not password:
            QMessageBox.warning(self, "输入错误", "用户名和密码不能为空!")
            return

        # 这里应该是实际的验证逻辑，例如:
        # - 数据库查询
        # - API调用
        # - 本地验证
        if self.validate_credentials(username, password):
            self.save_credentials()
            self.accept()  # 登录成功，关闭对话框并返回QDialog.Accepted
        else:
            QMessageBox.warning(self, "登录失败", "用户名或密码错误!")
            self.password_edit.clear()
            self.password_edit.setFocus()

    def auto_login(self):
        # 自动登录尝试
        if self.validate_credentials(self.username_edit.text(), self.password_edit.text()):
            self.accept()

    def validate_credentials(self, username, password):
        # 这里实现实际的验证逻辑
        # 示例: 简单的硬编码验证
        valid_users = {
            "admin": "admin123",
            "user": "user123"
        }

        return username in valid_users and valid_users[username] == password